<?php
/*
  Microblog bot for game release notifications
  Copyright (C) 2017  Alexander Yakovlev

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Source;

use \Game;

class Questbook extends Source {
  public $title = "Библиотека книг-игр";
  protected function parse() {
    $string = $this->get_text('http://quest-book.ru/directory/rss/');
    $service = new \Sabre\Xml\Service();
    $service->elementMap = [
      '{}item' => function(\Sabre\Xml\Reader $reader) {
        return \Sabre\Xml\Deserializer\keyValue($reader, '');
      },
      '{}channel' => function(\Sabre\Xml\Reader $reader) {
        return \Sabre\Xml\Deserializer\repeatingElements($reader, '{}item');
      },
    ];
    try {
      $games = $service->parse($string)[0]['value'];
    } catch (\Sabre\Xml\LibXMLException $e) {
      echo $e->getMessage();
      echo $e->getTraceAsString();
      return "";
    }
    unset($string);
    foreach ($games as $gameBlock) {
      $date = strtotime($gameBlock['pubDate']);
      if ($date < $this->period) continue;
      $game = new Game;
      $game->title = trim($gameBlock['title']);
      $game->url = trim($gameBlock['link']);
      $game->description = trim($gameBlock['description']);
      $this->games[] = $game;
    }
  }
}
